package com.sojson.serversocket.config.handler.business;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sojson.serversocket.config.handler.business.data.ServerSocketHandlerGetDosageData;
import com.sojson.serversocket.config.handler.business.data.ServerSocketHandlerGetStatusData;
import com.sojson.serversocket.util.ServerSocketUtil;
import com.sojson.serversocket.util.enums.EServerSocketGetDataType;
import com.sojson.util.HexUtil;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * ServerSocket业务包处理器(获取数据)
 *
 * @author liu
 * @date 2024-05-30
 */
@Slf4j
@Component
public class ServerSocketHandlerGetData {

    @Autowired
    private ServerSocketHandlerGetDosageData dosageData;
    @Autowired
    private ServerSocketHandlerGetStatusData statusData;

    public void run(ChannelHandlerContext ctx, Byte[] barr, String addrRever, String data) {
        // 帧长度
        int len = data.length() / 2;
        // 数据长度域
        String daLen = data.substring(9 * 2, 10 * 2);
        // 数据域
        String da = data.substring(10 * 2, (len - 2) * 2);
        // 校验码
        String verifyCode = data.substring((len - 2) * 2, (len - 1) * 2);

        HexUtil.dataLenVerify(da, daLen, 1);
        HexUtil.dataVerify(data, verifyCode, ServerSocketUtil.HEAD_BUSINESS, (len - 2) * 2);

        if (da.startsWith(EServerSocketGetDataType.DOSAGE.getAddThirtyThreeReverse())) {
            log.info(new StringBuilder("ServerSocket收到电表数据包: ").append(addrRever).append(",").append(data).toString());
            dosageData.run(ctx, da);
        } else if (da.startsWith(EServerSocketGetDataType.STATUS.getAddThirtyThreeReverse())) {
            log.info(new StringBuilder("ServerSocket收到电表状态包: ").append(addrRever).append(",").append(data).toString());
            statusData.run(ctx, barr, addrRever, da);
        } else {
            log.info("此功能未实现");
        }
    }

    public void error(ChannelHandlerContext ctx, String addrRever, String data) {
        log.info(new StringBuilder("ServerSocket收到电表数据异常包: ").append(addrRever).append(",").append(data).toString());
        // TODO
    }

}